import {useRef, useState} from "react";
import Modal, {ModalInstanceType} from "@/conponments/Modal";
import {useNavigate} from "react-router-dom";
import {useRequest} from "@/utils/useRequest.tsx";

type ResponseType = {
    token: string
    name: string
}

function Login() {
    const [phoneNumber, setPhoneNumber] = useState('')
    const [password, setPassword] = useState('')
    const modalRef = useRef<ModalInstanceType>(null)
    const {request} = useRequest<ResponseType>()
    const navigate = useNavigate()

    async function handleSubmitBtnClick() {
        if (!phoneNumber) {
            modalRef.current?.showMessage('请输入手机号');
            return;
        }
        if (!password) {
            modalRef.current?.showMessage('请输入密码');
            return;
        }

        try {
            const response = await request({
                url: '/api/login',
                method: 'POST',
                data: {phoneNumber, password}
            });
            localStorage.setItem('token', response.token);
            localStorage.setItem('name', response.name);
            console.log('登录成功, 用户名:', response.name);
            navigate('/home');
        } catch (e) {
            modalRef.current?.showMessage(e.message);
        }
    }


    return <>
        <div className="form">
            <div className="form-item">
                <div className="form-item-title">手机号</div>
                <input type="text" className="form-item-content" placeholder="请输入手机号" value={phoneNumber}
                       onChange={(e) => setPhoneNumber(e.target.value)}/>
            </div>
            <div className="form-item">
                <div className="form-item-title">密码</div>
                <input type="password" className="form-item-content" placeholder="请输入密码" value={password}
                       onChange={(e) => setPassword(e.target.value)}/>
            </div>
        </div>
        <div className="submit" onClick={handleSubmitBtnClick}>
            登陆
        </div>
        <p className="notice">
            *登陆即表示您已同意使用条款及隐私政策
        </p>
        <Modal ref={modalRef}/>
    </>
}

export default Login

